import requests
import time
import sys

api_domain = "http://localhost:8000"

def signup(session, username, password):
    resp = session.post(f'{api_domain}/auth/signup', json={
        "username": username,
        "password": password,
    })
    print(f"Signup status: {resp.status_code}")
    try:
        print(f"Signup response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Signup response: {resp.text}")
    return resp

def login(session, username, password):
    resp = session.post(f'{api_domain}/auth/login',json={
        "username": username,
        "password": password,
    })
    print(f"Login status: {resp.status_code}")
    try:
        print(f"Login response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Login response: {resp.text}")
    return resp

def change_password(session, access_token, old_password, new_password):
    resp = session.post(f'{api_domain}/auth/change-password', 
        headers={"Authorization": f"Bearer {access_token}"},
        json={
            "old_password": old_password,
            "new_password": new_password,
    })
    print(f"Change password status: {resp.status_code}")
    try:
        print(f"Change password response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Change password response: {resp.text}")
    return resp

def generate_reset_password_link(session, email):
    resp = session.post(f'{api_domain}/auth/admin/generate-reset-password-link', json={
        "email": email,
    })
    print(f"Generate reset password link status: {resp.status_code}")
    try:
        print(f"Generate reset password link response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Generate reset password link response: {resp.text}")
    return resp

def get_reset_link_for_ui(session, email):
    resp = session.post(f'{api_domain}/auth/admin/generate-reset-password-link-for-ui', json={
        "email": email,
    })
    print(f"Generate reset password UI link status: {resp.status_code}")
    try:
        print(f"Generate reset password UI link response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Generate reset password UI link response: {resp.text}")
    return resp

def reset_password_with_token(session, token, new_password):
    resp = session.post(f'{api_domain}/auth/reset-password/form', json={
        "token": token,
        "newPassword": new_password,
    })
    print(f"Reset password with token status: {resp.status_code}")
    try:
        print(f"Reset password with token response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Reset password with token response: {resp.text}")
    return resp

def demo_change_pwd():
    with requests.Session() as session:
        # unique_email = f"test+{int(time.time())}@example.com"
        unique_email = f"test+1751954520@example.com"
        old_password = "password123"
        new_password = "NewPassword123!"
        print(f"--- Using email: {unique_email} ---")

        # 1. Sign up a new user
        # signup(session, unique_email, old_password)

        # 2. Log in with the old password
        login_resp = login(session, unique_email, old_password)
        access_token = login_resp.json()['accessToken']

        # 3. Change the password
        change_password(session, access_token, old_password, new_password)

        # 4. Try to log in with the old password (should fail)
        print("\n--- Attempting login with old password (should fail) ---")
        with requests.Session() as new_session:
            login(new_session, unique_email, old_password)

        # 5. Log in with the new password (should succeed)
        print("\n--- Attempting login with new password (should succeed) ---")
        with requests.Session() as new_session:
            login(new_session, unique_email, new_password)

        # 6. Generate reset password link (admin function)
        print("\n--- Generating reset password link (admin function) ---")
        generate_reset_password_link(session, unique_email)

def copy_token_reset():
    unique_email = f"test+1751954520@example.com"
    new_password_for_reset = "Anewpassword1!"  # This is the new password the user will set

    with requests.Session() as session:
        print(f"--- Using email: {unique_email} ---")

        # 1. Admin generates reset password link
        print("""
    --- Admin generating reset password link ---""")
        reset_link_resp = generate_reset_password_link(session, unique_email)
        reset_token = None
        if reset_link_resp.status_code == 200:
            # Extract token from the printed link in server logs (manual step for now)
            # In a real scenario, this would be sent via email
            print("Please check the server logs for the reset password link and extract the token.")
            # For automated testing, we'd parse the link from the server logs directly.
            # For now, we'll still ask for manual input to ensure the server side is working.
            reset_token = input("Please paste the reset token from the server logs (ONLY the token part): ").strip()

        if not reset_token:
            print("Failed to get reset token. Exiting.")
            sys.exit()

        # 2. User resets password using the token
        print("""
    --- User resetting password with token ---""")
        reset_password_with_token(session, reset_token, new_password_for_reset)

        # 3. User attempts to log in with the new password
        print("\n--- Attempting login with new password after reset ---")
        with requests.Session() as new_session:
            login(new_session, unique_email, new_password_for_reset)

        # 4. User attempts to log in with the old password (should fail)
        print("\n--- Attempting login with old password (should fail) ---")
        with requests.Session() as new_session:
            login(new_session, unique_email, "password123")  # 假设旧密码是 password123


def reset_link():
    unique_email = f"test+1751954520@example.com"
    new_password_for_reset = "Anewpassword!"  # This is the new password the user will set

    with requests.Session() as session:
        print(f"--- Using email: {unique_email} ---")

        # Admin generates reset password UI link
        print("""
    --- Admin generating reset password UI link ---""")
        ui_link_resp = get_reset_link_for_ui(session, unique_email)
        if ui_link_resp.status_code == 200:
            reset_ui_link = ui_link_resp.json().get('reset_link')
            print(f"Please send this link to the user: {reset_ui_link}")
            print("User should open this link in a browser to reset their password.")
        else:
            print("Failed to generate reset password UI link.")

        # The following section demonstrates the API-based password reset flow.
        # You can uncomment the call to copy_token_reset() if you wish to test this flow.
        # copy_token_reset()
if __name__ == "__main__":
    unique_email = f"test+1751954520@example.com"
    resp = requests.post(f'{api_domain}/auth/login',json={
        "username": unique_email,
        "password": 'Aui2password!',
    })
    print(f"Login status: {resp.status_code}")
    try:
        print(f"Login response: {resp.json()}")
    except requests.exceptions.JSONDecodeError:
        print(f"Login response: {resp.text}")

